<template>
  <div class="chosse-image-wrap">
    <div class="input-wrap">
      <div class="toast">银行卡信息识别</div>
      <img :src="captureImg || cover" alt="" />
      <input
        ref="fileInput"
        class="fileInput"
        name="fileInput"
        type="file"
        @change="onChange($event)"
        accept="image/*"
      />
    </div>
    <image-capture
      @cancel="cancel()"
      @confirm="confirm($event)"
      ref="capture"
    ></image-capture>
  </div>
</template>

<script>
/**
 * 组件负责点击进行拍照或相册选取，自行调用截图组件，最终返回截图并压缩后的base64文件
 * @input {img} cover        传入封面图cover，自适应铺满父级宽度,高度跟随图片比例
 * captureMaxSize 进行指定size的压缩后，返回小于等于且最接近阈值大小的图片文件
 * @success  完成回调（file）
 * @resetImg 第二次开始选择图片会触发
 */
import {
  filetoDataURL,
  dataURLtoBolb,
  compressToSize,
  bolbToFile,
} from "@/utils/imgTools";
import { Dialog } from "vant";
import ImageCapture from "@/components/imageCapture";

export default {
  name: "ChosseBank",
  components: {
    ImageCapture,
    [Dialog.name]: Dialog,
  },
  props: ["cover", "typeKey"],
  data() {
    return {
      captureImg: undefined,
      captureMaxSize: 1, // 进行指定size的压缩后，返回小于等于且最接近阈值大小的图片文件
      originMaxSize: 3, // 用于保留一张较大的图片用于最终附件上传（小图用于信息识别）
      inactive: false,
      fileName: "",
      fileType: "",
    };
  },
  methods: {
    reset() {
      this.captureImg = undefined;
      this.inactive = false;
      this.fileName = "";
      this.fileType = "";
    },
    // 选择图片
    onChange(e) {
      if (this.inactive) {
        // 第二次开始重选图片会触发
        this.$emit("resetImg", this.typeKey);
      }
      this.inactive = true;
      const file = e.target.files[0];
      this.fileName = file.name;
      this.fileType = file.type;

      if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG|JPEG)$/.test(e.target.value)) {
        Dialog.alert({
          title: "格式错误",
          message: "请选择正确的图片格式",
          theme: "round-button",
          confirmButtonText: "确定",
        });
        return;
      }
      filetoDataURL(file).then((res) => {
        this.showCaputer(res);
      });
    },

    // 调用截图插件并传入图片
    showCaputer(data) {
      this.$refs.capture.show(data);
    },
    // 取消截图
    cancel() {
      this.$refs.fileInput.value = ""; // 清除input状态，否则再次选择同一张图无法再次出发onchange
    },
    // 截图完成
    confirm(data) {
      // this.captureImg = data;
      this.$refs.fileInput.value = "";
      this.$Loading.show("正在处理图片...");
      // 转成文件后开始压缩
      dataURLtoBolb(data).then((file) => {
        console.log(file, 10444);
        // 处理大尺寸图
        const p1 = new Promise((resolve, reject) => {
          this.handerImgCompress(file, this.originMaxSize).then((res) => {
            resolve(res);
          });
        });
        // 处理小尺寸图
        const p2 = new Promise((resolve, reject) => {
          this.handerImgCompress(file, this.captureMaxSize).then((res) => {
            resolve(res);
          });
        });
        Promise.all([p1, p2]).then((res) => {
          console.log(res, 144);
          this.$Loading.hidden();
          this.$emit("success", {
            smallImg: res[1],
            largerImg: res[0],
            typeKey: this.typeKey,
          });
        });
      });
    },
    // 进行执行的图片压缩后返回file文件
    handerImgCompress(
      file,
      maxSize,
      fileName = this.fileName,
      fileType = this.fileType
    ) {
      return new Promise((resolve, reject) => {
        maxSize = maxSize * 1024; // 统一转成kb，便于观测
        // 大于指定size(M)进行压缩
        // alert('需要压缩（kb）:' + file.size / 1024)
        // alert('预期输出尺寸（kb）：' + maxSize)
        console.log(file, maxSize, file.size / 1024, maxSize, 134);
        if (file.size / 1024 > maxSize) {
          compressToSize(file, maxSize).then((res) => {
            bolbToFile(res, fileName, fileType).then((file) => {
              // alert('压缩完成（kb）:' + file.size / 1024)
              console.log(file, 144);
              resolve(file);
            });
          });
        } else {
          bolbToFile(file, fileName, fileType).then((file) => {
            resolve(file);
          });
        }
      });
    },
  },
};
</script>

<style lang='stylus' scoped>
.chosse-image-wrap
  width 100%
  height 100%
  .input-wrap
    width 100%
    height 100%
    position relative
    border-radius 4px
    overflow hidden
    .toast
      width 100%
      height 22px
      background rgba(245, 98, 41, 0.5)
      text-align center
      font-size 12px
      color white
      line-height 22px
      position absolute
      left 0
      top 0
    .fileInput
      position absolute
      left 0
      right 0
      height 100%
      width 100%
      z-index 999
      border none
      opacity 0
      box-sizing border-box
    img
      width 100%
</style>